/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} [cFormat='{y}-{m}-{d} {h}:{i}:{s}']
 * @returns {string | null}
 */
export function parseTime(time, cFormat = '{y}-{m}-{d} {h}:{i}:{s}') {
  if (!time) return null;

  let date = (typeof time === 'object') ? time :
    (typeof time === 'string' && /^[0-9]+$/.test(time)) ? new Date(parseInt(time)) :
      (typeof time === 'number' && time.toString().length === 10) ? new Date(time * 1000) :
        new Date(time.replace(/-/g, '/')); // Support Safari

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: ['日', '一', '二', '三', '四'][date.getDay()]
  };

  return cFormat.replace(/{([ymdhisa])+}/g, (result, key) =>
    formatObj[key].toString().padStart(2, '0')
  );
}

export function formatTime(time, option) {
  time = ((typeof time === 'string' && time.length === 10) ? parseInt(time) * 1000 : +time);
  const d = new Date(time);
  const now = Date.now();
  const diff = (now - d) / 1000;

  if (diff < 30) return '刚刚';
  if (diff < 3600) return `${Math.ceil(diff / 60)}分钟前`;
  if (diff < 3600 * 24) return `${Math.ceil(diff / 3600)}小时前`;
  if (diff < 3600 * 24 * 2) return '1天前';

  return parseTime(time, option || `{y}-{m}-{d} {h}:{i}:{s}`);
}
export function param2Obj(url) {
  const searchParams = new URLSearchParams(url.split('?')[1]);
  return Object.fromEntries(searchParams.entries());
}
